package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;

import com.zzyl.nursing.vo.CheckInElderVo;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住表Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住表
     *
     * @param id 入住表主键
     * @return 入住表
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住表列表
     *
     * @param checkIn 入住表
     * @return 入住表
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住表
     *
     * @param checkIn 入住表
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住表
     *
     * @param checkIn 入住表
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住表
     *
     * @param ids 需要删除的入住表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住表信息
     *
     * @param id 入住表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     *
     * @param checkInApplyDto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //判断是否已经入住
        //根据身份证号查询老人
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus,1)
        );
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new RuntimeException("该老人已入住");
        }

        //更新床状态 已入住
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //保存、更新老人信息
        elder = insertOrUpdate(checkInApplyDto.getCheckInElderDto(), bed);

        // 生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();

        //新增签约办理
        insertContract(contractNo, elder, checkInApplyDto);

        //新增入住信息
        CheckIn checkIn =insertCheckIn(elder, checkInApplyDto);

        //新增入住配置信息
        insertCheckInConfig(checkIn, checkInApplyDto);
    }

    /**
     * 新增入住配置信息
     *
     * @param checkIn
     * @param checkInApplyDto
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     *
     * @param elder
     * @param checkInApplyDto
     * @return
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0L);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约办理
     *
     * @param elder
     * @param checkInApplyDto
     */
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();
        //属性拷贝
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        //状态，开始时间，结束时间
        //签约时间小于当前时间，合同生效中
        LocalDateTime startTime = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endTime = checkInApplyDto.getCheckInConfigDto().getEndDate();
        Integer status = startTime.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(Long.valueOf(status));
        contract.setStartDate(startTime);
        contract.setEndDate(endTime);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人信息
     *
     * @param checkInElderDto
     * @param bed
     * @return
     */
    private Elder insertOrUpdate(CheckInElderDto checkInElderDto, Bed bed) {
        //准备老人的数据
        Elder elder = new Elder();
        //拷贝数据
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        //查询老人信息，身份证号查询，状态不为一
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).ne(Elder::getStatus, 1);
        Elder elderDb = elderMapper.selectOne(lambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(elderDb)) {
            //修改
            elderMapper.updateById(elder);
        } else {
            //新增
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 入住详情
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public CheckInDetailVo detail(Long id) {
        // 查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        if (ObjectUtils.isNotEmpty(checkIn)) {
            // 查询老人信息
            Elder elder = elderMapper.selectById(checkIn.getElderId());
            CheckInElderVo checkInElderVo = new CheckInElderVo();
            if (ObjectUtils.isNotEmpty(elder)) {
                BeanUtils.copyProperties(elder, checkInElderVo);
            }
            checkInDetailVo.setCheckInElderVo(checkInElderVo);

            // 查询家属信息
            List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();
            if (ObjectUtils.isNotEmpty(checkIn.getRemark())) {
                List<ElderFamilyDto> elderFamilyDtoList = JSON.parseArray(checkIn.getRemark(), ElderFamilyDto.class);
                for (ElderFamilyDto elderFamilyDto : elderFamilyDtoList) {
                    ElderFamilyVo elderFamilyVo = new ElderFamilyVo();
                    BeanUtils.copyProperties(elderFamilyDto, elderFamilyVo);
                    elderFamilyVoList.add(elderFamilyVo);
                }
            }
            checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);

            // 查询入住配置信息
            CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery()
                    .eq(CheckInConfig::getCheckInId, checkIn.getId()));
            CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
            if (ObjectUtils.isNotEmpty(checkInConfig)) {
                BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
            }
            checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

            // 查询签约办理信息
            Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                    .eq(Contract::getElderId, checkIn.getElderId())
                    .eq(Contract::getStartDate, checkIn.getStartDate())
                    .eq(Contract::getEndDate, checkIn.getEndDate()));
            checkInDetailVo.setContract(contract);
        }

        return checkInDetailVo;
    }
}
